package com.wyk.controller;

import com.netflix.loadbalancer.reactive.ExecutionInfo;
import com.wyk.bean.Payment;
import com.wyk.common.Result;
import com.wyk.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/**视图层
 * @author WangYuKai
 * @Date 2022/5/12
 * @apiNote
 */
@RestController
@Slf4j
public class PaymentController {
    //注入service层
    @Autowired
    private PaymentService paymentService;
    //注入访问接口路径
    @Value("${server.port}")
    private String serverPort;

    //注入服务发现
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public Result addPayment(@RequestBody Payment payment){
        int i = paymentService.create(payment);
        if(i == 0){
            log.info("插入结果：" + i);
            return new Result(500,"添加失败");
        }
        log.info("插入结果：" + i);
        return new Result(200,"添加成功 :serverPort" +  serverPort ,i);
    }

    @GetMapping("/payment/{id}")
    public Result getPaymentById(@PathVariable("id") Integer id){
        Payment paymentById = paymentService.getPaymentById(id);
        if(paymentById != null){
            log.info("查询成功 :" + paymentById);
            return new Result(200,"查询成功 : serverPort" + serverPort,paymentById);
        }
            log.info("查询失败 :" + paymentById);
        return new Result(500,"查询失败");
    }

    //获取微服务信息
    @GetMapping("/payment/discovery")
    public Object discovery(){
        //获取微服务信息
        List<String> services = discoveryClient.getServices();
        services.forEach(service -> {
            log.info("*******1******" + service);
        });

        //获取指定微服务信息
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-ZHIFU-SERVICE");
        instances.forEach(instance -> {
            log.info("*************" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        });
        return services;
    }

    @GetMapping("/payment/lb")
    public String getPaymentLb(){
        return serverPort;
    }

    //测试超时控制
    @GetMapping("/payment/timeout")
    public String getPaymentTimeOut(){
        //休息5秒
        try{TimeUnit.SECONDS.sleep(3);}catch (InterruptedException e){e.printStackTrace();};
        return serverPort;
    }
}
